package cn.jly.ssm;

import cn.jly.ssm.config.SpringMvcConfig;
import cn.jly.ssm.filters.LogFilter;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import java.nio.charset.StandardCharsets;

/**
 * WebInit 的作用类似于 web.xml，这个类需要实现 WebApplicationInitializer 接口，
 * 并实现接口中的方法，当项目启动时，onStartup 方法会被自动执行，我们可以在这个方法中做一些项目初始化操作，
 * 例如加载 SpringMVC 容器，添加过滤器，添加 Listener、添加 Servlet 等。
 *
 * @author lanyangji
 * @description 相当于web.xml
 * @date 2020/12/10 下午 5:47
 */
public class WebInit implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        final AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        // 加载配置类
        applicationContext.register(SpringMvcConfig.class);
        // 添加dispatcherServlet
        final ServletRegistration.Dynamic springmvc = servletContext.addServlet("springmvc", new DispatcherServlet(applicationContext));
        // 给dispatcher添加路径映射
        springmvc.addMapping("/");
        // 给 DispatcherServlet 添加启动时机
        springmvc.setLoadOnStartup(1);

        // 注册自定义filter，这里可以体会到spring boot的好处
        final FilterRegistration.Dynamic codeFilter = servletContext.addFilter("logFilter", LogFilter.class);
        codeFilter.addMappingForUrlPatterns(null, false, "/*");

        // 中文乱码
        final FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter", CharacterEncodingFilter.class);
        characterEncodingFilter.setInitParameter("encoding", StandardCharsets.UTF_8.name());
        characterEncodingFilter.setInitParameter("forceRequestEncoding", String.valueOf(true));
        characterEncodingFilter.setInitParameter("forceResponseEncoding", String.valueOf(true));
        characterEncodingFilter.addMappingForUrlPatterns(null, false, "/*");
    }
}
